﻿<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Game Flappy Bird</title>
        <link href="css/templatemo_style.css" rel="stylesheet" type="text/css" />
        <style type="text/css">
            <!--
            .chat_wrapper {
                width: 600px;
                height: 350px;
                margin-right: auto;
                margin-left: auto;
                background: #CCCCCC;
                border: 1px solid #999999;
                padding: 10px;
                font: 14px 'lucida grande',tahoma,verdana,arial,sans-serif;
            }
            .chat_wrapper .message_box {
                background: #FFFFFF;
                height: 250px;
                overflow: auto;
                padding: 10px;
                border: 1px solid #999999;
            }
            .chat_wrapper .panel input{
                padding: 2px 2px 2px 5px;                
                font-size: 14px;
            }
            .system_msg{color: #BDBDBD;font-style: italic;}
            .user_name{font-weight:bold;}
            .user_message{color: #298bff;}
            -->
        </style>
    </head>
    <body>

 <div>
            <div id="templatemo_wrapper">

                <div id="templatemo_header">
                    <div id="site_title">
                        <h1><a>
                                <strong >Flappy bird</strong>
                                <span  style="color: #FF0; font-size: 16px">Điều đơn giản làm nên kỳ tích!</span>
                            </a></h1>                
                    </div> <!-- end of site_title -->

                    <!- Kiểm tra các nút bấm ->
                    <div  align = "center" style ="color: yellow; font-size: 16px;">
                        <?php
                        /* @var $_POST type */
                        $con = mysql_connect("localhost", "root", "");
                        mysql_select_db("ltm", $con);
                        $count = 0;
                        $arrayusername = array(1000);
                        $arraypassword = array(1000);
                        $sql = "select * from user";
                        $query = mysql_query($sql);
                        if (mysql_num_rows($query) == 0) {
                            
                        } else {

                            while ($row = mysql_fetch_array($query)) {
                                $arrayusername[$count] = $row["username"];
                                $arraypassword[$count] = $row["password"];
                                $count++;
                            }
                        }
                        session_start();
                        if (isset($_POST['dangnhap1'])) {
                            //Kiểm username đả nhập có trong username không.
                            $ktuser = 0;
                            $ktpass = 0;
                            $usercount;
                            $username = $_POST['username'];
                            $password = $_POST['password'];
                            if ($username == NULL || $password == NULL) {
                                echo "Bạn Chưa Nhập Username Hoặc Password";
                            } else {
                                for ($i = 0; $i < $count; $i++) {
                                    if ($arrayusername[$i] == $username) {
                                        $usercount = $i;
                                        $ktuser = 1;
                                        break;
                                    }
                                }
                                if ($ktuser == 1) {
                                    if ($arraypassword[$usercount] == $password) {
                                        $ktpass = 1;
                                    }
                                }
                                if ($ktpass == 1 && $ktuser == 1) {
                                    //echo "Bạn Đăng Nhập Thành Công";
                                    $_SESSION['tmp'] = true;
                                    $_SESSION['username1'] = $username;
                                } else if ($ktuser == 1 && $ktpass == 0) {
                                    echo "Mật khẩu bị sai";
                                } else if ($ktuser == 0) {
                                    echo "Username không tồn tại";
                                }
                            }
                        }

                        //Nhấn nút logout
                        if (isset($_POST['logout'])) {
                            unset($_SESSION['tmp']);
                            $_SESSION['username1'] = null;
                        }
                        ?>
                    </div>
                    <?php
                    if (isset($_SESSION['tmp']) == false) {
                        ?>

                        <!- Hiển thị form đăng nhập->
                        <form method="POST" id="social_box2">
                            <table style="width: 550px">
                                <tr align="center"  style="font-size: 12px; color: #0FF">
                                    <td >Tên Đăng Nhập</td>
                                    <td><input type="text" name="username" placeholder="Tên đăng nhập"></td> 
                                    <td>Mật khẩu</td>
                                    <td><input type="password" name="password" placeholder="Mật khẩu"/></td>
                                </tr>
                                <tr align="center">
                                    <td>
                                        <a href="account/accountForget.php" style="font-size: 14px"><u>Quên mật khẩu</u></a>
                                    </td>
                                    <td>
                                        <input type="submit" name="dangnhap1" value="Đăng Nhập" style="font-size:14px; color: #000; border: none; background: url(images/login.png); width:100px; height: 30px"/>
                                    </td> 
                                    <td>

                                    </td>
                                    <td>
                                        <a href="account/register.php"> <input type="button" name="dangky" value="Đăng ký" style="font-size:14px; border: none; background: url(images/register.png); width:100px; height: 30px"/></a>
                                    </td>
                                </tr>
                            </table>
                        </form>
                        <?php
                    } else {
                        ?>

                        <form method="POST" id="social_box2">
                            <table align="center">
                                <tr>
                                    <td>
                                        <label> 
                                            <?php
                                            echo "Xin Chào:";
                                            echo "<label id='lbUser'>" . $_SESSION['username1'] . "</label>";
                                            ?>
                                        </label>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <input type="submit" name="logout" value="Đăng xuất" style="font-size:14px; color: #000; border: none; background: url(images/login.png); width:100px; height: 30px"/>
                                    </td>
                                </tr>     
                            </table>
                        </form>
                        <?php
                    }
                    ?>
                    <!- End Hiển Thị Form Đăng Nhập ->

                    <ul id="social_box">
                        <li><a href="http://www.facebook.com"><img src="images/facebook.png" alt="facebook" /></a></li>
                        <li><a href="https://twitter.com/"><img src="images/twitter.png" alt="twitter" /></a></li>               
                    </ul>

                </div>

                <div id="templatemo_menu">
                    <ul>
                        <li><a href="index.php">Chơi game</a></li>
                        <li><a href="rank.php">Xếp hạng</a></li>
                        <li><a href="account.php">Tài khoản</a></li>
                        <li><a href="chat.php"  class="current">Trò chuyện</a></li>
                    </ul>    	
                </div> <!-- end of templatemo_menu -->

                <div id="templatemo_slider_wrapper"></div>

                <div id="account">
                    <table border = "2px">
                        <tr align ="center" style="font-size: 16px; color: greenyellow;">
                            <td id="chatFriend">
                                Bạn bè đang trò chuyện: ' tất cả mọi người '.
                            </td>
                            <td>
                                Danh sách trò chuyện.
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <div class="chat_wrapper">
                                    <div id="messageBox"><div class="message_box" id="message_box"></div></div>
                                    <p>&nbsp;</p>
                                    <div class="panel">                                
                                        <input type="text" name="message" id="message" placeholder="Tin nhắn."  style="width:100%" />
                                        <div  align = "center">
                                            <button id="btSend" style="font-size: 16px; color: red">Gửi tin nhắn</button>
                                            <button onclick="deleteMessage()" style="font-size: 16px; color: red">Xóa tin nhắn</button>
                                        </div>
                                    </div>
                                </div>  
                            </td>
                            <td>
                                <select id="selectChat" style= "font-size: 15px; width: 200px; height: 370px" size="2" onchange="changeChat()">                                    
                                    <option selected value="0">Trò chuyện với tất cả</option> 
                                </select>
                            </td>
                        </tr>
                    </table>
                </div>                
                <div class="cleaner"></div> 
                <div id="templatemo_footer">Designed by Trần Văn Công - Nguyễn Minh Khanh.</div>

            </div> <!-- end of wrapper -->
        </div> <!-- end of wrapper_outer -->
      
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

        <script language="javascript" type="text/javascript">
            var selectChat = document.getElementById("selectChat");
            var chatFriend = "all";
            var messageBefore = "";
            function changeChat() {
                saveMessage();
                var len = selectChat.length;
                for (var i = 0; i < len; i++) {
                    if (selectChat[i].selected) {
                        if (i == 0)
                            chatFriend = "all";
                        else
                            chatFriend = selectChat[i].innerHTML;
                    }
                }
                changeFriend();
            }
            function deleteMessage(){        
                document.getElementById("messageBox").innerHTML = '<div class="message_box" id="message_box"></div>';
                messageFocus();
            }
            function saveMessage(){
                var message = document.getElementById("message_box").innerHTML;
                var index = listUser.indexOf(chatFriend);
                if(index == -1){
                    listMessage.push(message);
                    listUser.push(chatFriend);
                }
                else listMessage[index] =  message;
            }
            function changeFriend(){
                var index = listUser.indexOf(chatFriend);
                document.getElementById("messageBox").innerHTML = '<div class="message_box" id="message_box"></div>';
                $('#message_box').append(listMessage[index]);
                autoscroll();
                var tmpFriend = chatFriend;
                if(chatFriend == 'all') tmpFriend = "tất cả mọi người";
                document.getElementById("chatFriend").innerHTML = "Bạn bè đang trò chuyện: ' " + tmpFriend + " '.";
                messageFocus();
            }
            function messageFocus() {
                document.getElementById('message').focus();
            }
            function sendMessage() {
                var mymessage = $('#message').val(); //get message text
                if (mymessage == "") { //emtpy message?
                    return;
                }
                else if(mymessage == messageBefore) mymessage += " ";
                if (userName != 'No name')
                {
                    //prepare json data
                    var msg = {
                        message: mymessage,
                        name: userName,
                        color: userColor,
                        type: 'message',
                        friend: chatFriend,
                    };
                    //convert and send data to server
                    websocket.send(JSON.stringify(msg));
                }
                else
                    alert("Bạn phải đăng nhập để trò chuyện.");
            }
            function autoscroll(){
                $log = $('#message_box');
                $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;                                
            }
            function connectServer() {
                if (userName != 'No name') {
                    //create a new WebSocket object.
                    var wsUri = "ws://localhost:9000";
                    websocket = new WebSocket(wsUri);

                    websocket.onopen = function(ev) { // connection is open 
                    }
                    //#### Message received from server?
                    websocket.onmessage = function(ev) {
                        if (userName != 'No name') {
                            var msg = JSON.parse(ev.data); //PHP sends Json data
                            var type = msg.type; //message type
                            if (type == 'connected')
                            {
                                var msg = {
                                    name: userName,
                                    type: 'connected',
                                };
                                //convert and send data to server
                                websocket.send(JSON.stringify(msg));
                            }
                            else if(type == 'color') userColor = msg.color;
                            else{
                                var uname = msg.name; //user name
                                if (type == 'usermsg')
                                {                                
                                    var umsg = msg.message; //message text
                                    messageBefore = umsg;
                                    var ucolor = msg.color; //color
                                    var friend = msg.friend;
                                    if (friend == userName) {
                                        var tmpFriend = uname; 
                                        if(chatFriend != tmpFriend){
                                            var len = selectChat.length;
                                            for (var i = 1; i < len; i++) {
                                                if (selectChat[i].innerHTML == uname) {
                                                    selectChat.selectedIndex = i;
                                                    saveMessage();
                                                    chatFriend = tmpFriend;
                                                    changeFriend();
                                                    break;
                                                }
                                            }
                                        }
                                        $('#message_box').append("<div><span class=\"user_name\" style=\"color:#" + ucolor + "\">" + uname + "</span> : <span class=\"user_message\">" + umsg + "</span></div>");
                                    }
                                    else if(friend == 'all'){
                                        selectChat.selectedIndex = 0;
                                        saveMessage();
                                        chatFriend = 'all';
                                        changeFriend();                                        
                                        $('#message_box').append("<div><span class=\"user_name\" style=\"color:#" + ucolor + "\">" + uname + "</span> : <span class=\"user_message\">" + umsg + "</span></div>");
                                    }
                                    else if (uname == userName)
                                        $('#message_box').append("<div><span class=\"user_name\" style=\"color:#" + ucolor + "\">" + uname + "</span> : <span class=\"user_message\">" + umsg + "</span></div>");
                                    autoscroll();
                                }
                                else if (type == 'friend' && userName != uname) {     
                                    var i = 0, len = selectChat.length;
                                    for (; i < len; i++) {
                                        if (selectChat[i].innerHTML == uname)
                                            break;
                                    }
                                    if (i == len) {
                                        var option = document.createElement("option");
                                        option.text = uname;
                                        selectChat.add(option);
                                    }
                                }
                                else if (type == 'disconnected') {        
                                    var i = 0, len = selectChat.length;
                                    for (; i < len; i++) {
                                        if (selectChat[i].innerHTML == uname) {
                                            selectChat.remove(i);
                                            chatFriend = "all";
                                            selectChat.selectedIndex = 0;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        $('#message').val(''); //reset text
                    };

                    websocket.onerror = function(ev) {
                        
                    };
                    websocket.onclose = function(ev) {     
                         websocket.close();
                         setTimeout(connectServer, 1000);
                    };
                }
                $('#message').keyup(function(evt) { //use clicks message send button	
                    if (evt.keyCode == 13)
                        sendMessage();
                });
                $('#btSend').click(function() { //use clicks message send button	
                    sendMessage();
                    messageFocus();
                });
            }
            $(document).ready(function() {
                listUser = ["all"];
                listMessage = [""];
                var tmp;
                if (tmp = document.getElementById("lbUser")) {
                    userName = tmp.innerHTML;
                }
                else
                    userName = "No name";
                connectServer();
                messageFocus(); 
            });
        </script>
    </body>
</html>